<?php


namespace app\home\controller;

use app\home\model\Attendance as AttendanceModel;
use app\home\model\AttendanceDetail;
use app\home\model\AttendanceOvertime;
use app\home\model\WechatDepartment;
use app\home\model\WechatUser;
use app\home\model\WechatUserTag;
use think\Db;

/**
 * 考勤打卡功能模块
 * Class Attendance
 * @package app\home\controller
 */
class Attendance extends Base
{
    protected $userid;
    protected $permission;
    protected $user;
    public function _initialize()
    {
        parent::_initialize();
        $this->anonymous();
        $this->jssdk();
        //判断用户状态
        $this->userid = session('userId');
        $res = WechatUserTag::where(['userid' => $this->userid])->find();
        if($res) {
            switch ($res['tagid']) {
                case 1: //总经理
                    $permission = 1;
                    break;
                case 2: //副总
                    $permission = 2;
                    break;
                case 3: //科室长
                    $permission = 3;
                    break;
                case 4: //考勤上报组
                    $permission = 4;
                    break;
                default: //普通员工
                    $permission = 5;
                    break;
            }
        }else {
            $permission = 5;
        }
        $this->permission = $permission;
        $this->user = $this->getTopDepartment($this->userid);
    }

    /**
     * 考勤首页
     */
    public function index () {
        $map = [
            'userid' => $this->userid,
            'tagid' => 4
        ];
        $user = WechatUserTag::where($map)->find();
        if($user) {
            $this->assign('is_permission',1); //考勤上报权限
        }else {
            $this->assign('is_permission',0); //无权限上报
        }
        return $this->fetch();
    }

    /**
     * 考勤上报
     * @return mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function work () {
        $time = input('time',time());
        $is_punch = input('is_punch',1);
        $start_time = strtotime(date("Y-m-d 00:00:00",$time));
        $end_time = strtotime(date("Y-m-d 23:59:59",$time));

        $AttendanceModel = new AttendanceModel();
        $AttendanceDetailModel = new AttendanceDetail();

        $map = [
            'userid' => $this->userid,
            'create_time' => ['between',[$start_time,$end_time]]
        ];
        $is_exist = $AttendanceModel->where($map)->find();
        $user = $this->user;
        if($is_exist) {  //当天已申报
            $list = $AttendanceDetailModel->getPunchList($is_punch,1,$user['top_id'],$time);
        }else { //当天未申报
            $list = $AttendanceDetailModel->getPunchList($is_punch,0,$user['top_id'],$time);
        }
        if(IS_POST) {
            if($list) {
                return $this->success("获取成功","",$list);
            }else {
                return $this->error("获取数据失败");
            }
        }else {
            $this->assign('list',json_encode($list));
            //是否当天已经上传
            if($is_exist) {
                $this->assign('is_exist',1);
            }else {
                $this->assign('is_exist',0);
            }
            return $this->fetch();
        }

    }

    /**
     * 考勤提交
     */
    public function publish() {
        $start_time = strtotime(date("Y-m-d 00:00:00",time()));
        $end_time = strtotime(date("Y-m-d 23:59:59",time()));

        $AttendanceModel = new AttendanceModel();
        $AttendanceDetailModel = new AttendanceDetail();
        if(IS_POST) {
            $post = input('post.');
            if($post) {
                $user = $this->user;
                $map = [
                    'top_id' => $user['top_id'],
                    'create_time' => ['between',[$start_time,$end_time]],
                ];
                $is_exist = $AttendanceModel->where($map)->find();
                if($is_exist) {
                    return $this->error("当天考勤记录已存在,请勿重复提交");
                }else {
                    $user['create_time'] = time();
                    $user['attendance_time'] = date("Y-m-d",time()+24*60*60);
                    $res = $AttendanceModel->create($user);
                    if($res) {
                        $return = [];
                        foreach ($post['data'] as $value) {
                            $value['create_time'] = time();
                            $value['attendance_time'] = date("Y-m-d",time()+24*60*60);
                            $value['pid'] = $res['id'];
                            $info = $AttendanceDetailModel->create($value);
                            $return[] = $info;
                        }
                        return $this->success("提交成功","",$return);
                    }else {
                        return $this->error("提交失败");
                    }
                }
            }else {
                return $this->error("数据传值失败");
            }
        }
    }

    /**
     * 加班考勤
     */
    public function overtime () {
        $Model = new AttendanceOvertime();
        $user = $this->user;
        $start_time = strtotime(date("Y-m-d 00:00:00",time()-24*60*60));
        $end_time = strtotime(date("Y-m-d 23:59:59",time()));
        $map = [
            'userid' => $user['userid'],
            'start_time' => ['between',[$start_time,$end_time]]
        ];
        $res = $Model->where($map)->order('start_time desc')->find();
        if(!empty($res) && $res['status'] == 0) {
            $result = $res;
        }else {
            $result = ['status' => -1];
        }
        if(IS_POST) {
            $type = input('type'); //1加班 2外勤
            $address = input('address');
            if($result['status'] > -1) { //存在则是签退
                $data['end_time'] = time();
                $data['end_address'] = $address;
                $data['type'] = $type;
                $data['status'] = 1;
                $info = $Model->update($data,['id' => $res['id']]);
                if($info) {
                    return $this->success("签退成功","",$info);
                }else {
                    return $this->error("签退失败");
                }
            }else { //不存在是签到
                $data['type'] = $type;
                $data['start_time'] = time();
                $data['start_address'] = $address;
                $data['userid'] = $user['userid'];
                $data['username'] = $user['username'];
                $data['top_id'] = $user['top_id'];
                $data['departmentid'] = $user['departmentid'];
                $data['status'] = 0;
                $info = $Model->create($data);
                if($info) {
                    return $this->success("签到成功","",$info);
                }else {
                    return $this->error("签到失败");
                }
            }
        }else {
            $this->assign('detail',json_encode($result));
            return $this->fetch();
        }
    }

    /**
     * 我的加班列表
     * @return mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function overtime_record()
    {
        $length = input('length',0);
        $list = AttendanceOvertime::where('userid','=',$this->userid)->order('start_time','DESC')->limit($length,8)->select();
        foreach ($list as $key => $value) {
            if(empty($value->end_time)) {
                $list[$key]['hour'] = 0;
            }else {
                $hour = round(($value->end_time - $value->start_time) / 3600,2);
                $list[$key]['hour'] = $hour;
            }
            $list[$key]['start_time'] = date("Y-m-d H:i:s",$value['start_time']);
            $list[$key]['end_time'] = date("Y-m-d H:i:s",$value['end_time']);
        }
        int_to_string($list,['type' => ["1" => "加班","2" => "外勤"]]);
        if(IS_POST) {
            if($list) {
                return $this->success("加载成功","",$list);
            }else {
                return $this->error("加载失败");
            }
        }else {
            $this->assign('list',json_encode($list));
            return $this->fetch();
        }
    }


    /**
     * 考勤情况
     */
    public function record () {
        //判断是否办公室主任
        $map = [
            'tagid' => 5,
            'userid' => $this->userid
        ];
        $is_depart = WechatUserTag::where($map)->find();
        //获取考勤信息
        $time = input('time',time());
        $Model = new AttendanceDetail();
        if($this->permission < 3 || $is_depart) { //获取领导权限，查看所有数据
            $list = [
                'count' => [
                    'total' => 0,
                    'status_1' => 0,
                    'status_2' => 0,
                    'status_0' => 0,
                ],
            ];
            //获取全部科室
            $department = WechatDepartment::where(['parentid' => 1])->order('`order` desc')->select();
            foreach ($department as $value) {
                $user = $Model->getViewList($value['id'],$time);
                $list['count']['total'] += $user['count']['total'];
                $list['count']['status_1'] += $user['count']['status_1'];
                $list['count']['status_2'] += $user['count']['status_2'];
                $list['count']['status_0'] += $user['count']['status_0'];
                foreach ($user['department'] as $v) {
                    $list['department'][] = $v;
                }
            }
        }else { //对应用户查看自己科室的考勤情况
            $user = $this->getTopDepartment($this->userid);
            $list = $Model->getViewList($user['top_id'],$time);
        }
        if(IS_POST) {
            if($list) {
                return $this->success("获取成功","",$list);
            }else {
                return $this->error("获取失败");
            }
        }else {
            $this->assign('list',json_encode($list));
            return $this->fetch();
        }

    }

    /**
     * 获取当前用户所属科室
     */
    private function getTopDepartment($userid) {
        $userModel = new WechatUser();
        $departmentModel = new WechatDepartment();
        $user = $userModel->where(['userid' => $userid])->find();
        $department = $departmentModel->where(['id' => $user['department']])->find();
        $depart = $department['id'];
        //查找顶级部门id
        if($department['parentid'] == 1) {
           $top_depart = $department['id'];
        }else {
            $department2 = $departmentModel->where(['id' => $department['parentid']])->find();
            if($department2['parentid'] == 1) {
                $top_depart = $department2['id'];
            }else {
                $department3 = $departmentModel->where(['id' => $department2['parentid']])->find();
                if($department3['parentid'] == 1) {
                    $top_depart = $department3['id'];
                }else {
                    return $this->error("查找不到该用户所在科室！");
                }
            }
        }
        $return = [
            'userid' => $userid,
            'username' => $user['name'],
            'top_id' => $top_depart,
            'departmentid' => $depart,
        ];
        return $return;
    }
}
